<template>
  <div>
    <!-- 头部搜索 start -->
    <el-form ref="queryForm"
      class="query-form"
      :model="queryParams"
      size="small"
      :inline="true">
      <el-form-item label="状态"
        prop="status">
        <el-select v-model="queryParams.status"
          @change="handleQuery">
          <el-option key="all"
            label="全部"
            :value="10"/>
          <el-option
            label="已上架"
            :value="1" />
          <el-option
            label="待上架"
            :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="big-query" label="关键词"
        prop="keyword">
        <el-input v-model="queryParams.keyword"
          placeholder="输入权益ID、权益名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
          @clear="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          size="small"
          @click="handleQuery">搜索</el-button>
        <el-button size="small"
          @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 头部搜索 end -->

    <!-- 头部操作栏 start -->

    <el-button type="primary"
      icon="el-icon-plus"
      style="margin-bottom:10px"
      size="small"
      @click="handleAdd">新增</el-button>

    <!-- 头部操作栏 end -->

    <!-- 数据表格 start -->
    <el-table v-loading="loading"
      :data="rightsList">
      <el-table-column label="权益ID"
        min-width="100"
        prop="right_id" />
      <el-table-column label="权益名称"
        min-width="200"
        prop="name">
        <template slot-scope="scope">
          <pre>{{scope.row.name}}</pre>
        </template>
      </el-table-column>
      <el-table-column label="权益图标(设置中心)"
        min-width="200"

        prop="icon">
        <template slot-scope="scope">
          <el-image slot="reference"
            style="height: 36px;cursor: pointer;"
            :src="scope.row.icon"
            fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="权益图标(弹窗)"
        min-width="200"

        prop="p_icon">
        <template slot-scope="scope">
          <el-image slot="reference"
            style="height: 36px;cursor: pointer;"
            :src="scope.row.p_icon"
            fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="权益权重"
        min-width="120"

        sortable
        prop="weight" />
      <el-table-column label="状态"
        min-width="80"
        >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'"
            disable-transitions>{{ scope.row.status === 1 ? '已上架' : '待上架' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"
        width="170"
        fixed="right"

        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.status === 1"
            size="small"
            type="text"
            @click="handleSale(scope.row)">上架</el-button>
          <el-button
            size="small"
            type="text"
            :title="scope.row.appVersionText"
            @click="handleProject(scope.row)">发布</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button :disabled="scope.row.status === 1"
            size="small"
            type="text"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList" />
        <!-- 数据表格 end -->
      <!-- 添加或修改对话框 start -->
      <el-dialog :title="title"
        :visible.sync="open"
        width="850px"
        :close-on-click-modal="false"
        top="3vh">
        <el-form ref="form"
          :model="form"
          :rules="rules"
          label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="权益ID" prop="right_id">
                <el-input v-model.trim="form.right_id" :disabled="!isAddOpt" maxlength="15"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最低版本" prop="min_ver">
                <el-input v-model.trim="form.min_ver"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="权益名称"
                prop="name">
                <el-input v-model="form.name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="权重" prop="weight">
                <el-input-number v-model="form.weight" :precision="0" :min="0"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="权益描述"
                prop="desc">
                <el-input v-model="form.desc" type="textarea" :rows="2" maxlength="50"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="权益图标(设置中心)"
                prop="icon">
                <ImgUpload v-model="form.icon"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="权益图标(弹窗)"
                prop="p_icon">
                <ImgUpload v-model="form.p_icon"/>
              </el-form-item>
             </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="权益类型"
                prop="type">
                <el-select v-model="form.type">
                  <el-option label="普通权益" value="normal"></el-option>
                  <el-option label="赠送权益" value="give"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="form.type==='give'" label="计费单位"
                prop="charge_unit">
                <el-select v-model="form.charge_unit">
                  <el-option v-for="item in chargeUnitList" :key="item.unit_id" :label="item.internal_name" :value="item.unit_id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="非会员描述"
                prop="c_rule_desc">
                <el-input v-model="form.c_rule_desc" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="非会员使用规则"
                prop="c_rule">
                <el-radio-group v-model="form.c_rule">
                  <el-radio :key="1"
                    :label="1">无限</el-radio>
                  <el-radio :key="2"
                    :label="2">限量</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="非会员频次"
                prop="c_limit_rate">
                <el-radio-group v-model="form.c_limit_rate" :disabled="form.c_rule === 1">
                  <el-radio :key="1"
                    :label="1">每月</el-radio>
                  <el-radio :key="2"
                    :label="2">每天</el-radio>
                  <el-radio :key="3"
                    :label="3">总量</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="非会员数量"
                :required="form.c_rule === 2"
                :show-message="false"
                prop="c_limit_cond">
                <el-input-number v-model="form.c_limit_cond"
                 :disabled="form.c_rule === 1"></el-input-number>
                <span style="padding-left:10px">个/次</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="会员描述"
                prop="rule_desc">
                <el-input v-model="form.rule_desc" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员使用规则"
                prop="rule">
                <el-radio-group v-model="form.rule">
                  <el-radio :key="1"
                    :label="1">无限</el-radio>
                  <el-radio :key="2"
                    :label="2">限量</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="会员频次"
                prop="limit_rate">
                <el-radio-group v-model="form.limit_rate" :disabled="form.rule === 1">
                  <el-radio :key="1"
                    :label="1">每月</el-radio>
                  <el-radio :key="2"
                    :label="2">每天</el-radio>
                  <el-radio :key="3"
                    :label="3">总量</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员数量"
              :required="form.rule === 2"
              :show-message="false"
                prop="limit_cond">
                <el-input-number v-model="form.limit_cond"
                 :disabled="form.rule === 1"></el-input-number>
                <span style="padding-left:10px">个/次</span>
              </el-form-item>
             </el-col>
          </el-row>
        </el-form>
        <div slot="footer"
          class="dialog-footer">
          <el-button type="primary"
            @click="submitForm">确 认</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 添加或修改对话框 end -->

      <!-- 发布信息修改对话框 start -->
      <el-dialog title="发布信息修改"
        :visible.sync="openProject"
        width="820px"
        :close-on-click-modal="false">
        <el-form ref="projectForm"
          :model="projectForm"
          label-width="100px">

          <el-row v-for="(item,index) in projectForm.show_version" :key="index">
            <el-col :span="8">
              <el-form-item label="项目" :prop="'show_version.'+index+'.app_id'" :rules="{required: true, message: '项目不能为空', trigger: 'blur'}">
                <el-select v-model="item.app_id" placeholder="请选择">
                  <el-option v-for="itemb in permission_projectList" :key="itemb.app_id"
                    :label="itemb.name"
                    :value="itemb.app_id"
                    :disabled="disabledChoose(itemb,index)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="最低版本" :prop="'show_version.'+index+'.version'" :rules="{required: true, message: '最低版本不能为空', trigger: 'blur'}">
                <el-input v-model.trim="item.version" placeholder="最低版本"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="最高版本" :prop="'show_version.'+index+'.max_version'">
                <el-input v-model.trim="item.max_version" placeholder="最低版本"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="text" icon="el-icon-remove-outline" :disabled="projectForm.show_version.length<2" @click="delProject(index)" style="margin-left: 10px;"></el-button>
              <el-button type="text" icon="el-icon-circle-plus-outline" v-show="index===projectForm.show_version.length-1" @click="addProject"></el-button>
            </el-col>
          </el-row>

        </el-form>
        <div slot="footer"
          class="dialog-footer">
          <el-button type="primary"
            @click="submitProjectForm">确 认</el-button>
          <el-button @click="openProject = false">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 发布信息修改对话框 end -->

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ImgUpload from '@/components/img-upload'
import { listRights, addRights, delRights, updateRights, updateRightsVersion, updateSaleStatus } from '@/api/rights/rights'
import { getChargeUnit } from '@/api/system'
export default {
  name: 'Rights',
  components: {
    ImgUpload
  },
  data () {
    return {
      // 是否是添加操作
      isAddOpt: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 权益表格数据
      rightsList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 权益类别选项
      // 表单参数
      form: {
        right_id: null,
        min_ver: '',
        name: '',
        desc: '',
        weight: 0,
        icon: '',
        p_icon: '',
        type: 'normal',
        charge_unit: '',
        c_rule_desc: '',
        c_rule: 2,
        c_limit_rate: 3,
        c_limit_cond: undefined,
        rule_desc: '',
        rule: 2,
        limit_rate: 3,
        limit_cond: undefined
      },
      chargeUnitList: [],
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        keyword: undefined,
        status: 10
      },
      // 表单校验
      rules: {
        right_id: [
          { required: true, message: '权益ID不能为空', trigger: 'blur' },
          { pattern: /^\d+/, message: '只能输入数字', trigger: 'change' }
        ],
        name: [
          { required: true, message: '权益名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '权益类型不能为空', trigger: 'blur' }
        ],
        charge_unit: [
          { required: true, message: '计费单位不能为空', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '权益图标（设置中心）不能为空', trigger: 'blur' }
        ],
        p_icon: [
          { required: true, message: '权益图标（弹窗）不能为空', trigger: 'blur' }
        ],
        c_rule_desc: [
          { required: true, message: '非会员描述不能为空', trigger: 'blur' }
        ],
        rule_desc: [
          { required: true, message: '会员描述不能为空', trigger: 'blur' }
        ]
      },
      iconType: 0,
      openProject: false,
      projectForm: {
        right_id: null,
        show_version: []
      }
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    disabledChoose () {
      return function (item, index) {
        let findItemIndex = this.projectForm.show_version.findIndex(item2 => item2.app_id === item.app_id)
        return findItemIndex !== -1 && index !== findItemIndex
      }
    }
  },
  async created () {
    getChargeUnit().then(res => {
      this.chargeUnitList = res.data.list
    })
    this.getList()
  },
  methods: {
    /** 查询权益列表 */
    getList () {
      listRights(this.queryParams).then(response => {
        this.rightsList = (response.data.list || []).map(it => {
          it.appVersionText = (it.show_version || []).reduce((str, it, i) => {
            i && (str += '\n')
            str += this.$options.filters.translateToName(it.app_id, this.permission_projectList, 'app_id', 'name') + '：最低版本' + it.version
            return str
          }, '')
          return it
        })
        this.total = response.data.count || 0
      }
      ).finally(() => {
        this.loading = false
      })
    },
    /** 表单重置 */
    reset () {
      this.resetForm('form')
      this.form.charge_unit = ''
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.title = '添加权益'
      this.isAddOpt = true
    },
    /** 上架按钮操作 */
    handleSale (row) {
      this.$confirm('是否确认上架该权益？权益名：' + row.name, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateSaleStatus({ right_id: row.right_id, status: 1 }).then(() => {
          this.getList()
          this.msgSuccess('操作成功')
        })
      })
    },
    /** 修改版本控制 */
    handleProject (row) {
      this.resetForm('projectForm')
      this.projectForm.right_id = row.right_id
      this.projectForm.show_version = (row.show_version || []).map(it => Object.assign({}, it))
      if (!this.projectForm.show_version.length) {
        this.addProject()
      }
      this.openProject = true
    },
    delProject (i) {
      this.projectForm.show_version.splice(i, 1)
    },
    addProject () {
      this.projectForm.show_version.push({
        'app_id': null,
        'version': '',
        max_version: ''
      })
    },
    /** 提交项目版本控制 */
    submitProjectForm () {
      this.$refs['projectForm'].validate().then(() => {
        const params = Object.assign({}, this.projectForm)
        updateRightsVersion(params).then(response => {
          this.msgSuccess('修改成功')
          this.openProject = false
          this.getList()
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset()
      this.open = true
      this.title = '修改权益'
      this.isAddOpt = false
      this.$nextTick(() => {
        const keys = Object.keys(this.form)
        for (const item of keys) {
          this.form[item] = row[item]
        }
        this.form.id = row.id
        if (this.form.rule === 1) this.form.limit_cond = undefined
        if (this.form.c_rule === 1) this.form.c_limit_cond = undefined
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const params = Object.assign({}, this.form)
          if (params.rule === 1) {
            params.limit_cond = 0
          }
          if (params.c_rule === 1) {
            params.c_limit_cond = 0
          }
          params.limit_cond = params.limit_cond.toString()
          params.c_limit_cond = params.c_limit_cond.toString()
          if (!this.isAddOpt) {
            updateRights(params).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRights(params).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const rightsId = row.right_id
      const { pageIndex, pageSize } = this.queryParams
      this.$confirm(`是否确认删除该权益？权益名：${row.name}`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRights(rightsId).then(() => {
          this.queryParams.pageIndex = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
          this.getList()
          this.msgSuccess('删除成功')
        })
      })
    }
  }
}
</script>
<style lang="scss">
.el-table .el-image {
  /deep/.el-image__inner {
    max-height: 36px;
  }
}
</style>
